package com.qingfeng.provide.service;

import com.qingfeng.core.aop.exception.HttpException;
import com.qingfeng.core.config.redis.RedisUtil;
import com.qingfeng.core.constant.CacheValueConstant;
import com.qingfeng.core.constant.RedisKeyConstant;
import com.qingfeng.core.dao.qingfeng.FileDao;
import com.qingfeng.core.dao.qingfeng.UserDao;
import com.qingfeng.core.entity.qingfeng.User;
import com.qingfeng.core.mapper.qingfeng.UserMapper;
import com.qingfeng.core.utils.DesUtil;
import com.qingfeng.core.utils.UuidUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @description:
 * @author:LWY
 * @date: 2017/11/15 18:22
 * @modified:
 */
@Service
public class UserService {
    private static Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    UserDao userDao;
    @Autowired
    UserMapper userMapper;

    @Autowired
    FileDao fileDao;

    /**
     * 登录，验证码
     *
     * @param phone 手机
     * @param auth  授权密钥（验证码或者密码）
     * @param type  登录类型
     * @return
     */
    public Map<String, Object> login(String phone, String auth, String type) {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = null;
        if (Objects.equals("1", type)) {
            //获取验证码
            String str = RedisUtil.getStr(RedisKeyConstant.LOGIN_VERI_CODE + phone);
            if (StringUtils.isEmpty(str)) {
                throw new HttpException("验证码已经失效，请重新验证");
            }
            if (!Objects.equals(str, auth)) {
                throw new HttpException("验证码不正确，请重新验证");
            }
            //删除验证码
            RedisUtil.del(RedisKeyConstant.LOGIN_VERI_CODE + phone);
            //登录成功
            user = userDao.get(phone);
        } else {
            auth = DesUtil.encryptBasedDes(auth);
            user = userDao.get(phone, auth);
            if (user == null) {
                throw new HttpException("手机或者密码不正确");
            }
        }
        if (user.getState() == 2) {
            throw new HttpException("该账号已经被禁止登录了");
        }
        //生成token(uuid),以后每次请求都要带上这个token验证身份，存入redis
        String token = UuidUtil.generatorUUID();
        RedisUtil.add(RedisKeyConstant.USER_TOKEN_ID + user.getId(), token);
        map.put("token", token);
        map.put("id", user.getId());
        return map;
    }

    /**
     * 发送验证码
     *
     * @param phone 手机
     * @param type  类型（1：登录、2：找回密码、3：绑定手机.....）
     */
    public String auth(String phone, String type) {
        StringBuffer code = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            code.append(new Random().nextInt(10));
        }
        logger.info(phone + "的验证码：" + code.toString());
        if (Objects.equals("1", type)) {
            //登录
            RedisUtil.add(RedisKeyConstant.LOGIN_VERI_CODE + phone, code, 180);
        } else if (Objects.equals("2", type)) {
            //找回密码
            RedisUtil.add(RedisKeyConstant.FORGET_VERI_CODE + phone, code, 180);
        } else if (Objects.equals("3", type)) {
            //绑定手机
            RedisUtil.add(RedisKeyConstant.BIND_VERI_CODE + phone, code, 180);
        }
        return code.toString();
    }

    /**
     * 找回密码
     *
     * @param phone 手机号码
     * @param auth  验证码
     * @param pwd   密码
     */
    public void forget(String phone, String auth, String pwd) {
        //获取验证码
        String str = RedisUtil.getStr(RedisKeyConstant.FORGET_VERI_CODE + phone);
        if (!Objects.equals(str, auth)) {
            throw new HttpException("验证码不正确");
        }
        //删除验证码
        RedisUtil.del(RedisKeyConstant.FORGET_VERI_CODE + phone);
        //修改成功
        userDao.forget(phone, pwd);
    }


    /**
     * 绑定手机号码
     *
     * @param phone 手机号码
     * @param auth  验证码
     * @param id    用户id
     */
    @CacheEvict(value = "'" + CacheValueConstant.USER + "'", key = "'" + RedisKeyConstant.USER_ID + "'+#id")
    public void bindPhone(String phone, String auth, String id) {
        //获取验证码
        String str = RedisUtil.getStr(RedisKeyConstant.BIND_VERI_CODE + phone);
        if (!Objects.equals(str, auth)) {
            throw new HttpException("验证码不正确");
        }
        //删除验证码
        RedisUtil.del(RedisKeyConstant.BIND_VERI_CODE + phone);
        //修改成功
        userDao.bindPhone(phone, id);
    }


    /**
     * 获取用户信息
     *
     * @param id 用户id
     * @return
     */
    @Cacheable(value = "'" + CacheValueConstant.USER + "'", key = "'" + RedisKeyConstant.USER_ID + "'+#id", unless = "#result==null")
    public Map<String, Object> userinfo(String id) {
        Map<String, Object> userinfo = userMapper.userinfo(id);
        userinfo.remove("pwd");
        return userinfo;
    }

    /**
     * 保存用户信息
     *
     * @param id        用户id
     * @param nick_name 昵称
     * @param sex       性别
     * @param grade_id  年级id
     * @param major     专业
     * @param specialty 特长
     */
    @CacheEvict(value = "'" + CacheValueConstant.USER + "'", key = "'" + RedisKeyConstant.USER_ID + "'+#id")
    public void saveInfo(String id, String nick_name, String sex, String grade_id, String major, String specialty) {
        if (StringUtils.isEmpty(sex)) {
            sex = "0";
        }
        userDao.saveInfo(id, nick_name, Integer.valueOf(sex), grade_id, major, specialty);
    }

    /**
     * 上传证件
     *
     * @param user_id 用户id
     * @param type    1：学生证、2：身份证
     * @param files   文件
     */
    public void saveCredential(String user_id, Integer type, List<MultipartFile> files) {
        for (MultipartFile file : files) {
            String contentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            //todo 上传文件
            String url = "";
            if (type == 1) {
                fileDao.save(3, 2, "", user_id, user_id, url);
            } else if (type == 2) {
                fileDao.save(4, 2, "", user_id, user_id, url);
            }
        }
    }
}
